﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IEnumerableBatchExtensionMethod.cs" company="DST Nexdox">
//   Copyright (c) DST Nexdox. All rights reserved.
// </copyright>
// <summary>
//   Defines the IEnumerableBatchExtensionMethod type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Extensions
{
  using System;
  using System.Collections.Generic;

  public static class IEnumerableBatchExtensionMethod
  {
    public static IEnumerable<List<T>> Batch<T>(this IEnumerable<T> items, Int32 batchSize)
    {
      IEnumerator<T> enumerator = items.GetEnumerator();

      while (enumerator.MoveNext())
      {
        yield return SingleBatch(enumerator, batchSize);
      }
    }

    private static List<T> SingleBatch<T>(IEnumerator<T> enumerator, Int32 batchSize)
    {
      Int32 numItems = 0;
      var items = new List<T>();

      do
      {
        numItems++;
        items.Add(enumerator.Current);
      }
      while (numItems != batchSize && enumerator.MoveNext());

      return items;
    }
  }
}
